Do first

  1. Navigate to the 1-functions/ folder.
  2. Open 1-functions.Rproj as an RStudio project in a new R session. (Click on 1-functions.Rproj in RStudio’s file manager.)
  3. Check that your working directory is correct. It should be 1-functions/.
basename(getwd()) # Should be "1-functions"
## [1] "1-functions"
  1. Run the code chunk below. (Click on the green arrow on the right.)

About

In this notebook, we will explore Keras models that predict customer behavior, and we will express our implementation in 7 custom functions. These functions are the essential building blocks of the drake workflows to come.

  1. split_data(): read the customer churn data and split it into a training set and a test set.
  2. prepare_recipe(): get the data ready for the Keras models.
  3. define_model(): define a Keras model.
  4. train_model(): call define_model() to define a Keras model, fit it to the testing data, and return the fitted model object.
  5. test_accuracy(): get the test accuracy of a fitted Keras model.
  6. test_model(): call train_model() and test_accuracy() to train a model and summarize its testing accuracy.
  7. train_best_model(): train the highest-accuracy model we have found so far.

Customer churn

Using the IBM Watson Telco Customer Churn dataset, we will train deep neural networks to classify customers. The goal is to predict who will cancel their subscription services such as internet and television. Cancellation, or “customer churn”, is a problem that companies care about monitoring. For additional background on this example, please read https://blogs.rstudio.com/tensorflow/posts/2018-01-11-keras-customer-churn.

Packages

Our functions will need the following R packages. Run the code chunk below to load them now. (Click on the green arrow on the right.)

# Build and train deep neural nets.
# https://keras.rstudio.com/index.html
library(keras)

# Custom data preprocessing procedures.
# https://tidymodels.github.io/recipes/
library(recipes)

# Data resampling. We will use it to split the customer churn dataset
# into training and test sets for our deep learning models.
# https://tidymodels.github.io/rsample
library(rsample)

# Multiple packages that support clean code and tidy data.
# https://tidyverse.tidyverse.org/
library(tidyverse)

# Tidy methods to measure model performance.
# We will use it to compute accuracy on the testing set.
# https://tidymodels.github.io/yardstick
library(yardstick)

Check if TensorFlow is installed. The code below should display the TensorFlow version. Do not worry about other console messages.

library(tensorflow)
tf_version()
#> [1] '1.13'

split_data()

For machine learning, we need to split the customers (rows) into a training dataset and a testing dataset.

split_data <- function(churn_file) {
  read_csv(churn_file, col_types = cols()) %>%
    initial_split(prop = 0.3) # from the rsample package
}

Try it out.

churn_data <- split_data("../data/customer_churn.csv")

The training set has 2113 customers (rows) and the testing set has 4930.

print(churn_data)
#> <2113/4930/7043>

Functions from rsample can recover the training and testing sets.

training(churn_data)
testing(churn_data)

The dataset has 21 variables (columns).

# View(training(churn_data))
glimpse(training(churn_data))
#> Observations: 2,113
#> Variables: 21
#> $ customerID       <chr> "7795-CFOCW", "9237-HQITU", "6713-OKOMC", "8091-TTVA…
#> $ gender           <chr> "Male", "Female", "Female", "Male", "Male", "Female"…
#> $ SeniorCitizen    <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
#> $ Partner          <chr> "No", "No", "No", "Yes", "No", "Yes", "No", "No", "Y…
#> $ Dependents       <chr> "No", "No", "No", "No", "No", "Yes", "No", "Yes", "Y…
#> $ tenure           <dbl> 45, 2, 10, 58, 49, 69, 52, 71, 10, 1, 58, 72, 17, 1,…
#> $ PhoneService     <chr> "No", "Yes", "No", "Yes", "Yes", "Yes", "Yes", "Yes"…
#> $ MultipleLines    <chr> "No phone service", "No", "No phone service", "Yes",…
#> $ InternetService  <chr> "DSL", "Fiber optic", "DSL", "Fiber optic", "Fiber o…
#> $ OnlineSecurity   <chr> "Yes", "No", "Yes", "No", "No", "Yes", "No internet …
#> $ OnlineBackup     <chr> "No", "No", "No", "No", "Yes", "Yes", "No internet s…
#> $ DeviceProtection <chr> "Yes", "No", "No", "Yes", "Yes", "Yes", "No internet…
#> $ TechSupport      <chr> "Yes", "No", "No", "No", "No", "Yes", "No internet s…
#> $ StreamingTV      <chr> "No", "No", "No", "Yes", "Yes", "Yes", "No internet …
#> $ StreamingMovies  <chr> "No", "No", "No", "Yes", "Yes", "Yes", "No internet …
#> $ Contract         <chr> "One year", "Month-to-month", "Month-to-month", "One…
#> $ PaperlessBilling <chr> "No", "Yes", "No", "No", "Yes", "No", "No", "No", "N…
#> $ PaymentMethod    <chr> "Bank transfer (automatic)", "Electronic check", "Ma…
#> $ MonthlyCharges   <dbl> 42.30, 70.70, 29.75, 100.35, 103.70, 113.25, 20.65, …
#> $ TotalCharges     <dbl> 1840.75, 151.65, 301.90, 5681.10, 5036.30, 7895.15, …
#> $ Churn            <chr> "No", "Yes", "No", "No", "Yes", "No", "No", "No", "Y…

Churn is our response variable, and customerID identifies customers.

training(churn_data) %>%
  select(customerID, Churn) %>%
  print()
#> # A tibble: 2,113 x 2
#>    customerID Churn
#>    <chr>      <chr>
#>  1 7795-CFOCW No   
#>  2 9237-HQITU Yes  
#>  3 6713-OKOMC No   
#>  4 8091-TTVAX No   
#>  5 0280-XJGEX Yes  
#>  6 3655-SNQYZ No   
#>  7 8191-XWSZG No   
#>  8 9959-WOFKT No   
#>  9 4190-MFLUW Yes  
#> 10 1066-JKSGK Yes  
#> # … with 2,103 more rows

The rest of the variables are covariates.

prepare_recipe()

prepare_recipe() gets our data ready for our models. It accepts a data frame with a train/test and returns a recipe object generated by the recipes package.

prepare_recipe <- function(churn_data) {
  churn_data %>%
    # Just preprocess the training data.
    training() %>%
    # Start defining a new recipe.
    recipe(Churn ~ .) %>%
    # Remove the customerID variable from the data.
    step_rm(customerID) %>%
    # Remove missing values.
    step_naomit(all_outcomes(), all_predictors()) %>%
    # Partition the tenure variable into 6 bins.
    step_discretize(tenure, options = list(cuts = 6)) %>%
    # Take the log of TotalCharges to strengthen the association with Churn.
    step_log(TotalCharges) %>%
    # Encode the Churn variable as a 0-1 indicator variable.
    step_mutate(Churn = ifelse(Churn == "Yes", 1, 0)) %>%
    # Encode each categorical variable as a collection of 0-1 indicators.
    step_dummy(all_nominal(), -all_outcomes()) %>%
    # Center all covariates.
    step_center(all_predictors(), -all_outcomes()) %>%
    # Scale all covariates.
    step_scale(all_predictors(), -all_outcomes()) %>%
    # Run the recipe on the data.
    prep()
}

Let’s try out the function to make sure it works.

churn_recipe <- prepare_recipe(churn_data)
print(churn_recipe)
#> Data Recipe
#> 
#> Inputs:
#> 
#>       role #variables
#>    outcome          1
#>  predictor         20
#> 
#> Training data contained 2113 data points and 1 incomplete row. 
#> 
#> Operations:
#> 
#> Variables removed customerID [trained]
#> Removing rows with NA values in all_outcomes, all_predictors
#> Dummy variables from tenure [trained]
#> Log transformation on TotalCharges [trained]
#> Variable mutation for  Churn [trained]
#> Dummy variables from gender, Partner, Dependents, tenure, ... [trained]
#> Centering for SeniorCitizen, MonthlyCharges, ... [trained]
#> Scaling for SeniorCitizen, MonthlyCharges, ... [trained]

Later on, we will need to retrieve the preprocessed training data with juice().

juice(churn_recipe, all_outcomes())
juice(churn_recipe, all_predictors())

Keras will want our predictors to be in matrix form.

juice(churn_recipe, all_predictors(), composition = "matrix")[1:6, 1:4]
#>      SeniorCitizen MonthlyCharges TotalCharges gender_Male
#> [1,]    -0.4294568     -0.7273266    0.3692667   1.0295561
#> [2,]    -0.4294568      0.2171965   -1.2167130  -0.9708325
#> [3,]    -0.4294568     -1.1447126   -0.7792830  -0.9708325
#> [4,]    -0.4294568      1.2032918    1.0852529   1.0295561
#> [5,]    -0.4294568      1.3147056    1.0087140   1.0295561
#> [6,]    -0.4294568      1.6323181    1.2943386  -0.9708325

When we compute accuracy later on, we will use bake() to preprocess the testing data.

bake(churn_recipe, testing(churn_data))

define_model()

Before we fit a model, we need to define it. define_model() function encapsulates our Keras model definition. It serves as custom shorthand that will make our other functions easier to read.

define_model <- function(churn_recipe, units1, units2, act1, act2, act3) {
  input_shape <- ncol(
    juice(churn_recipe, all_predictors(), composition = "matrix")
  )
  keras_model_sequential() %>%
    layer_dense(
      units = units1,
      kernel_initializer = "uniform",
      activation = act1,
      input_shape = input_shape
    ) %>%
    layer_dropout(rate = 0.1) %>%
    layer_dense(
      units = units2,
      kernel_initializer = "uniform",
      activation = act2
    ) %>%
    layer_dropout(rate = 0.1) %>%
    layer_dense(
      units = 1,
      kernel_initializer = "uniform",
      activation = act3
    )
}

Let’s check if it returns the model definition we expect.

define_model(churn_recipe, 16, 16, "relu", "relu", "sigmoid") %>%
  print()
#> Model
#> ________________________________________________________________________________
#> Layer (type)                        Output Shape                    Param #     
#> ================================================================================
#> dense (Dense)                       (None, 16)                      576         
#> ________________________________________________________________________________
#> dropout (Dropout)                   (None, 16)                      0           
#> ________________________________________________________________________________
#> dense_1 (Dense)                     (None, 16)                      272         
#> ________________________________________________________________________________
#> dropout_1 (Dropout)                 (None, 16)                      0           
#> ________________________________________________________________________________
#> dense_2 (Dense)                     (None, 1)                       17          
#> ================================================================================
#> Total params: 865
#> Trainable params: 865
#> Non-trainable params: 0
#> ________________________________________________________________________________

train_model()

Next, we need to fit a model and return the fitted model object.

train_model <- function(
  churn_recipe,
  units1 = 16,
  units2 = 16,
  act1 = "relu",
  act2 = "relu",
  act3 = "sigmoid"
) {
  model <- define_model(churn_recipe, units1, units2, act1, act2, act3)
  compile(
    model,
    optimizer = "adam",
    loss = "binary_crossentropy",
    metrics = c("accuracy")
  )
  x_train_tbl <- juice(
    churn_recipe,
    all_predictors(),
    composition = "matrix"
  )
  y_train_vec <- juice(churn_recipe, all_outcomes()) %>%
    pull()
  fit(
    object = model,
    x = x_train_tbl,
    y = y_train_vec,
    batch_size = 32,
    epochs = 32,
    validation_split = 0.3,
    verbose = 0
  )
  model
}

Try it out.

model <- train_model(churn_recipe)

print(model)
#> Model
#> ________________________________________________________________________________
#> Layer (type)                        Output Shape                    Param #     
#> ================================================================================
#> dense_3 (Dense)                     (None, 16)                      576         
#> ________________________________________________________________________________
#> dropout_2 (Dropout)                 (None, 16)                      0           
#> ________________________________________________________________________________
#> dense_4 (Dense)                     (None, 16)                      272         
#> ________________________________________________________________________________
#> dropout_3 (Dropout)                 (None, 16)                      0           
#> ________________________________________________________________________________
#> dense_5 (Dense)                     (None, 1)                       17          
#> ================================================================================
#> Total params: 865
#> Trainable params: 865
#> Non-trainable params: 0
#> ________________________________________________________________________________

test_accuracy()

This function takes model object from train_model() and computes the accuracy on the testing data.

test_accuracy <- function(churn_data, churn_recipe, model) {
  testing_data <- bake(churn_recipe, testing(churn_data))
  x_test_tbl <- testing_data %>%
    select(-Churn) %>%
    as.matrix()
  y_test_vec <- testing_data %>%
    select(Churn) %>%
    pull()
  yhat_keras_class_vec <- model %>%
    predict_classes(x_test_tbl) %>%
    as.factor() %>%
    fct_recode(yes = "1", no = "0")
  yhat_keras_prob_vec <-
    model %>%
    predict_proba(x_test_tbl) %>%
    as.vector()
  test_truth <- y_test_vec %>%
    as.factor() %>%
    fct_recode(yes = "1", no = "0")
  estimates_keras_tbl <- tibble(
    truth = test_truth,
    estimate = yhat_keras_class_vec,
    class_prob = yhat_keras_prob_vec
  )
  estimates_keras_tbl %>%
    conf_mat(truth, estimate) %>%
    summary() %>%
    filter(.metric == "accuracy") %>%
    pull(.estimate)
}

Try it out.

test_accuracy(churn_data, churn_recipe, model)
#> [1] 0.7900407

test_model()

test_model() is the top-level modeling function we will use in drake. It trains a model and reports its accuracy on the test dataset. It uses the previously defined train_model() and test_accuracy() functions.

test_model <- function(
  churn_data,
  churn_recipe,
  units1 = 16,
  units2 = 16,
  act1 = "relu",
  act2 = "relu",
  act3 = "sigmoid"
) {
  model <- train_model(churn_recipe, units1, units2, act1, act2, act3)
  accuracy <- test_accuracy(churn_data, churn_recipe, model)
  tibble(
    accuracy = accuracy,
    units1 = units1,
    units2 = units2,
    act1 = act1,
    act2 = act2,
    act3 = act3
  )
}

Try it out.

run_relu <- test_model(act1 = "relu", churn_data, churn_recipe)
run_sigmoid <- test_model(act1 = "sigmoid", churn_data, churn_recipe)

run_relu

train_best_model()

Now, let’s train the model with the highest accuracy.

train_best_model <- function(best_run, churn_recipe) {
  train_model(
    churn_recipe,
    best_run$units1,
    best_run$units2,
    best_run$act1,
    best_run$act2,
    best_run$act3
  )
}

Try it out.

best_run <- bind_rows(run_relu, run_sigmoid) %>%
  filter(accuracy == max(accuracy))

train_best_model(best_run, churn_recipe = churn_recipe)
#> Model
#> ________________________________________________________________________________
#> Layer (type)                        Output Shape                    Param #     
#> ================================================================================
#> dense_12 (Dense)                    (None, 16)                      576         
#> ________________________________________________________________________________
#> dropout_8 (Dropout)                 (None, 16)                      0           
#> ________________________________________________________________________________
#> dense_13 (Dense)                    (None, 16)                      272         
#> ________________________________________________________________________________
#> dropout_9 (Dropout)                 (None, 16)                      0           
#> ________________________________________________________________________________
#> dense_14 (Dense)                    (None, 1)                       17          
#> ================================================================================
#> Total params: 865
#> Trainable params: 865
#> Non-trainable params: 0
#> ________________________________________________________________________________